<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/5/24
 * Time: 4:16 下午
 * description: GoodsBusiness.php
 */

namespace app\adminapi\business;

use app\common\model\GoodsImages;
use app\common\model\SpecGoods;
use think\db\exception\PDOException;
use think\facade\Db;
use think\Image;

/**
 * 商品业务逻辑类
 * Class GoodsBusiness
 * @package app\adminapi\business
 */
class GoodsBusiness
{
    /**
     * 商品列表
     */
    public static function list($limit){
        try {
            # 分类名称 模型关联查询多条件搜索
            $where = [];
            # 商品名称
            $goods_name = request()->get('goods_name');
            if (!empty($goods_name)) {
                $where[] = ['goods_name','LIKE',"$goods_name%"];
            }
            # 商品价格 最大值、最小值
            $goods_min_price = request()->get('goods_min_price');
            $goods_max_price = request()->get('goods_max_price');
            if ($goods_min_price>0) {
                $where[] = ['goods_price','>',$goods_min_price];
            }
            if ($goods_max_price>0) {
                $where[] = ['goods_price','<',$goods_max_price];
            }
            # 商品分类
            $cate_id = request()->get('cate_id',0);
            if (!is_numeric($cate_id)) {
                abort(2001,'商品分类只能是整数');
            }
            if ($cate_id > 0 ){
                $where[] = ['cate_id','=',$cate_id];
            }
            # 商品最新商品、或者价格排序 （默认是是否热卖进行排序）
            $sort_field = request()->get('sort_field','is_recommend');//是否推荐
            $sort_type = request()->get('sort_type','desc');// 客户端可以自定义 desc 1 asc 2
            if (!in_array($sort_type,['asc','desc'])) {
                abort(2001,'排序类型错误');
            }
            $list = \app\common\model\Goods::order($sort_field,$sort_type)->where($where)->with('category')->paginate($limit)->toArray();

            foreach ($list['data'] as $key => $value) {
//            unset($value['category']);// 只是销毁$value变量里面的category、错误
                unset($list['data'][$key]['category']);
            }
            return  $list;
        }catch (PDOException $PDOException) {
//            abort(2001,$PDOException->getMessage());// 开发过程中、查看具体的错误信息
            abort(2001,"参数错误");// 上线统一返回结果、参数错误
        }

    }

    /**
     * 添加商品
     */
    public static function addGoods($param){

        // 启动事务
        Db::startTrans();
        try {
            # 添加商品基本信息 goods
            // 构造商品的数据
            $goodsData = [
                'goods_name' => $param['goods_name'],
                'goods_logo' => $param['goods_logo'],
                'goods_price' => $param['goods_price'],
                'market_price' => $param['market_price'],
                'cate_id' => $param['cate_id'],
                'type_id' => $param['type_id'],
                'brand_id' => $param['brand_id'],
                'goods_desc' => remove_xss($param['goods_desc']),
//                。。。。
                'goods_attr' => json_encode($param['attr'],JSON_UNESCAPED_UNICODE)//属性值
            ];

            $goodsRes = \app\common\model\Goods::create($goodsData);
            $goods_id = $goodsRes->id;

            # 商品SKU信息 spec_goods

            $specGoodsModel = new SpecGoods();
            # 构造数据
            $specGoodsData = [];

            foreach ($param['item'] as $value) {
                $specGoodsData[] = [
                    'goods_id' => $goods_id,
                    'value_ids' => $value['value_ids'],
                    'value_names' => $value['value_names'],
                    'price' => $value['price'],
                    'cost_price' => $value['cost_price'],
                    'store_count' => $value['store_count'],
                ];
            }


            $specGoodsModel->saveAll($specGoodsData);

            # 商品相册 image
            $imageModel = new GoodsImages();
            $imageData = [];

            foreach ($param['goods_image'] as $image) {
                $imageInfo = pathinfo($image);//文件信息、里面有文件名、文件后缀
                $bigImage = Image::open('.'.$image);
                $filename = '.'.$imageInfo['dirname'].'/thumb_400_'.md5($imageInfo['filename']).'.'.$imageInfo['extension'];

                $bigImage->thumb(400,400)->save($filename);

                $imageData[] = [
                    'goods_id' => $goods_id,
                    'pics_big' => $image,// 大图 使用原图
                    'pics_sma' => trim($filename,'.'),// 小图 制作一个缩略图
                ];
            }

            $imageModel->saveAll($imageData);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();
            print_r($e->getCode());
            dd($e->getMessage());
            abort(2002,$e->getMessage());// 停止继续执行
        }
    }

    /**
     * 商品详情
     * bind方法只能用于一对一
     * hidden()隐藏关联属性
     * 分类的信息、相册、品牌的信息、sku信息、（类型、属性信息、规格信息）
     */
    public static function detail($id){

        $field = 'id,brand_id,type_id,cate_id,goods_name,goods_logo,goods_price,goods_attr';

        // 隐藏一个关联属性
//        $info = \app\common\model\Goods::field($field)->with(['category','brand','specGoods','images'])->hidden(['images.create_time'])->findOrEmpty($id)->toArray();
        // 隐藏多个关联属性
        $info = \app\common\model\Goods::field($field)
            ->with(['category','brand','specGoods','images'])
            ->hidden(['images' => ['create_time','update_time','delete_time']])
            ->hidden(['category' => ['create_time','update_time','delete_time']])
            ->findOrEmpty($id)
            ->toArray();
        dd($info);die();
        unset($info['category']);
        unset($info['brand']);
        # 模型的信息 前端可以直接通过type调用type详情接口进行查询

        $type_id = $info['type_id'];
        # 重新查询数据库

        $type_info = \app\common\model\Type::with(['attr','spec','spec.specValue'])->find($type_id)->toArray();

        $info['type_info'] = $type_info;

        return $info;
    }
}